global proc customReorderAttrUI() {
    if (`window -exists attrReorderWin`) deleteUI attrReorderWin;
    
    window -title "Attribute Organizer & Folders" -wh 350 500 attrReorderWin;
    columnLayout -adjustableColumn true -rowSpacing 5 -columnOffset "both" 10;
    
    text -label "1. Select Object\n2. Highlight Attribute\n3. Reorder or Add Folder" -align "center" -height 60;
    
    textScrollList -height 250 attrListWidget;
    
    // Reordering Controls
    rowLayout -numberOfColumns 2 -columnWidth2 165 165;
        button -label "Move to Bottom" -width 160 -bgc 0.2 0.3 0.4 -command "moveAttrToEnd()";
        button -label "Refresh List" -width 160 -command "refreshAttrList";
    setParent ..;

    separator -height 10 -style "shelf";

    // Folder Creation Controls
    text -label "Create Folder / Separator:" -align "left";
    rowLayout -numberOfColumns 2 -columnWidth2 220 100;
        textField -placeholderText "FOLDER_NAME" folderNameField;
        button -label "Add Folder" -width 90 -bgc 0.3 0.4 0.3 -command "addFolderAttr()";
    setParent ..;
    
    showWindow attrReorderWin;
    refreshAttrList();
}

global proc refreshAttrList() {
    string $sel[] = `ls -sl`;
    textScrollList -e -removeAll attrListWidget;
    
    if (size($sel) > 0) {
        string $attrs[] = `listAttr -userDefined $sel[0]`;
        for ($a in $attrs) {
            textScrollList -e -append $a attrListWidget;
        }
    }
}

global proc addFolderAttr() {
    string $sel[] = `ls -sl`;
    if (size($sel) == 0) { confirmDialog -title "Error" -message "Select an object first!"; return; }
    
    string $rawName = `textField -q -text folderNameField`;
    if ($rawName == "") $rawName = "SEPARATOR";
    
    string $folderName = ("___" + $rawName + "___");
    
    // Create an Enum attribute that acts as a visual divider
    addAttr -ln $folderName -at "enum" -en "----------:" $sel[0];
    setAttr -e -channelBox true ($sel[0] + "." + $folderName);
    setAttr -lock true ($sel[0] + "." + $folderName); // Lock it so user doesn't change "----------"
    
    textField -e -text "" folderNameField;
    refreshAttrList();
}

global proc moveAttrToEnd() {
    string $sel[] = `ls -sl`;
    if (size($sel) == 0) return;
    
    string $node = $sel[0];
    string $selectedAttrs[] = `textScrollList -q -selectItem attrListWidget`;
    if (size($selectedAttrs) == 0) return;
    
    for ($attr in $selectedAttrs) {
        // The Maya Reorder Trick:
        // Deleting an attribute and immediately undoing it 
        // forces Maya to place it at the end of the 'Extra Attributes' list.
        deleteAttr -at $attr $node;
        undo;
    }
    
    refreshAttrList();
    // Reselect the item in the UI
    textScrollList -e -selectItem $selectedAttrs[0] attrListWidget;
}

customReorderAttrUI();